package com.superb.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.superb.common.core.annotation.SuperbDataScope;
import com.superb.common.core.annotation.SuperbRestMapping;
import com.superb.common.core.model.Result;
import com.superb.common.database.entity.BaseEntity;
import com.superb.common.utils.StringUtils;
import com.superb.system.api.dto.Options;
import com.superb.system.api.entity.Organization;
import com.superb.system.api.entity.SystemRole;
import com.superb.system.api.entity.UserDataScope;
import com.superb.system.api.vo.UpdateScopeMain;
import com.superb.system.service.SystemOrganizationService;
import com.superb.system.service.SystemRoleService;
import com.superb.system.service.UserDataScopeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户数据权限范围
 * @Author: ajie
 * @CreateTime: 2024-7-3
 */
@SuperbDataScope
@SuperbRestMapping("/userDataScope")
@Tag(name = "用户数据权限范围")
@SaCheckPermission("system:dataScope:manage")
@ApiSupport(author = "阿杰：ajie20999@163.com", order = 7)
public class UserDataScopeController {

    @Resource
    private UserDataScopeService dataScopeService;
    @Resource
    private SystemRoleService roleService;
    @Resource
    private SystemOrganizationService organizationService;

    @GetMapping("list/{userId}")
    @ApiOperationSupport(order = 1)
    @Operation(summary = "用户数据权限查询", description = "权限: system:dataScope:manage<br>", parameters = {
            @Parameter(name = "userId", description = "用户id", required = true, in = ParameterIn.PATH)
    })
    public Result<List<UserDataScope>> listQuery(@PathVariable String userId) {
        LambdaQueryWrapper<UserDataScope> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserDataScope::getUserId, userId);
        // 默认部门在前
        lqw.orderByDesc(UserDataScope::getIsMain);
        List<UserDataScope> result = dataScopeService.list(lqw);
        for (UserDataScope dataScope : result) {
            String roleId = dataScope.getRoleId();
            if (StringUtils.isNotBlank(roleId)) {
                String[] roleIds = roleId.split(",");
                LambdaQueryWrapper<SystemRole> rlqw = new LambdaQueryWrapper<>();
                rlqw.select(SystemRole::getName, SystemRole::getId);
                rlqw.in(BaseEntity::getId, Arrays.asList(roleIds));
                List<SystemRole> list = roleService.list(rlqw);
                List<Options> roles = new ArrayList<>();
                for (SystemRole role : list) {
                    Options option = new Options();
                    option.setLabel(role.getName());
                    option.setValue(role.getId());
                    roles.add(option);
                }
                dataScope.setRoleIds(List.of(roleIds));
                dataScope.setRoles(roles);
            }
            String organId = dataScope.getDataScopeOrganId();
            // 数据权限自定义且部门不为空
            if (StringUtils.isNotBlank(organId) && dataScope.getDataScopeType() == 4) {
                String[] organIds = organId.split(",");
                LambdaQueryWrapper<Organization> rlqw = new LambdaQueryWrapper<>();
                rlqw.select(Organization::getName, Organization::getId);
                rlqw.in(BaseEntity::getId, Arrays.asList(organIds));
                List<Organization> list = organizationService.list(rlqw);
                List<Options> roles = new ArrayList<>();
                for (Organization organ : list) {
                    Options option = new Options();
                    option.setLabel(organ.getName());
                    option.setValue(organ.getId());
                    roles.add(option);
                }
                dataScope.setOrgans(roles);
            }
        }
        return Result.success(result);
    }

    @PostMapping("insert")
    @ApiOperationSupport(order = 2)
    @Operation(summary = "新增用户数据权限", description = "权限: system:dataScope:manage<br>")
    public Result<Boolean> insert(@RequestBody @Validated UserDataScope dataScope) {
        LambdaQueryWrapper<UserDataScope> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserDataScope::getUserId, dataScope.getUserId());
        lqw.eq(UserDataScope::getOrganId, dataScope.getOrganId());
        if (dataScopeService.count(lqw) > 0) {
            return Result.success("当前部门已存在数据权限，无法再次创建！");
        }
        if (dataScope.getDataScopeType() == 4) {
            List<Options> organs = dataScope.getOrgans();
            if (organs.size() < 1) {
                return Result.error("自定义数据权限部门不能为空！");
            }
            // 逗号分割的部门id
            dataScope.setDataScopeOrganId(organs.stream().map(Options::getValue).collect(Collectors.joining(",")));
        }
        if (!dataScope.getRoleIds().isEmpty() && dataScope.getRoleIds().size() > 0) {
            // 逗号分割角色id
            dataScope.setRoleId(String.join(",", dataScope.getRoleIds()));
        }
        if (dataScopeService.save(dataScope)) {
            return Result.success();
        }
        return Result.error();
    }

    @PostMapping("update")
    @ApiOperationSupport(order = 3)
    @Operation(summary = "修改用户数据权限", description = "权限: system:dataScope:manage<br>")
    public Result<Boolean> update(@RequestBody @Validated UserDataScope dataScope) {
        LambdaQueryWrapper<UserDataScope> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserDataScope::getUserId, dataScope.getUserId());
        lqw.eq(UserDataScope::getOrganId, dataScope.getOrganId());
        // 不算当前修改部门
        lqw.ne(UserDataScope::getId, dataScope.getId());
        if (dataScopeService.count(lqw) > 0) {
            return Result.success("当前部门已存在数据权限，修改时无法选中！");
        }
        if (dataScope.getDataScopeType() == 4) {
            List<Options> organs = dataScope.getOrgans();
            if (organs.size() < 1) {
                return Result.error("自定义数据权限部门不能为空！");
            }
            // 逗号分割的部门id
            dataScope.setDataScopeOrganId(organs.stream().map(Options::getValue).collect(Collectors.joining(",")));
        } else {
            dataScope.setDataScopeOrganId("");
        }
        if (!dataScope.getRoleIds().isEmpty() && dataScope.getRoleIds().size() > 0) {
            // 逗号分割角色id
            dataScope.setRoleId(String.join(",", dataScope.getRoleIds()));
        } else {
            dataScope.setRoleId("");
        }
        if (dataScopeService.updateById(dataScope)) {
            return Result.success();
        }
        return Result.error();
    }

    @PostMapping("updateMain")
    @ApiOperationSupport(order = 4)
    @Operation(summary = "用户数据权限是否默认", description = "权限: system:dataScope:manage<br>")
    public Result<Boolean> updateMain(@RequestBody @Validated UpdateScopeMain scopeMain) {
        if (scopeMain.getIsMain() == 1) {
            // 1.获取数据权限信息
            UserDataScope dataScope = dataScopeService.getById(scopeMain.getId());
            // 2.将该数据权限的用户其他数据权限设置为否
            LambdaUpdateWrapper<UserDataScope> luw = new LambdaUpdateWrapper<>();
            luw.set(UserDataScope::getIsMain, 0);
            luw.eq(UserDataScope::getUserId, dataScope.getUserId());
            dataScopeService.update(luw);
            // 3.将传递的id权限设置为默认
            UserDataScope entity = new UserDataScope();
            entity.setId(scopeMain.getId());
            entity.setIsMain(scopeMain.getIsMain());
            dataScopeService.updateById(entity);
        } else {
            LambdaUpdateWrapper<UserDataScope> luw = new LambdaUpdateWrapper<>();
            luw.set(UserDataScope::getIsMain, 0);
            luw.eq(BaseEntity::getId, scopeMain.getId());
            dataScopeService.update(luw);
        }
        return Result.success();
    }
}